package com.train.bizlog.core.aspect;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
import com.train.common.utils.filter.SensitiveFilterUtils;
import com.train.common.utils.servlet.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component
@Aspect
@Slf4j
public class OperLogAspect {

    @Pointcut("execution(public * com.train..facade..*Facade.*(..))")
    public void pointcut() {}

    @Before("pointcut()")
    public void doBefore(JoinPoint joinPoint) {
        //添加日志流水号
        MDC.put("LOG_ID", String.valueOf(System.currentTimeMillis() + RandomUtil.randomInt(3)));

        //获取请求接口信息
        log.info("请求ip是:{}", ServletUtils.getRequestIp());
        log.info("请求地址是:{}", ServletUtils.getRequestUrl());
        log.info("请求方式是:{}", ServletUtils.getRequestMethod());
        log.info("请求接口是:{}", joinPoint.getSignature().getName());

        Object[] args = joinPoint.getArgs();

        //排除文件类型参数, 不需要打印
        Object[] arguments = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            if (!(args[i] instanceof MultipartFile)) {
                arguments[i] = args[i];
            }
        }

        //打印参数, filter不需要序列化
        PropertyPreFilters.MySimplePropertyPreFilter filter = SensitiveFilterUtils.filter("mobile", "password", "email", "idCard");
        log.info("请求参数是:{}", JSONObject.toJSONString(arguments, filter));
    }

    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        PropertyPreFilters.MySimplePropertyPreFilter filter = SensitiveFilterUtils.filter("mobile", "password", "email", "idCard");
        log.info("返回结果是:{}", JSONObject.toJSONString(result, filter));
        log.info("=========执行结束,耗时是:{}ms=========", System.currentTimeMillis() - startTime);
        return result;
    }
}
